package service;

import dao.TaskDAO;
import domain.Task;
import org.springframework.stereotype.Service;
import util.DateComparator;
import util.SortedList;

import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.XMLFormatter;

/**
 * User: Алексей
 * Date: 21.11.12
 * Time: 13:42
 */
@Service
public class TaskManager {

    private TaskDAO dao;
    private static Logger log = Logger.getLogger(TaskManager.class.getName());

    public TaskManager() {
    }

    public void setDao(TaskDAO dao) {
        this.dao = dao;
    }

    public TaskManager(TaskDAO dao) {
        this.dao = dao;
        try {
            FileHandler fileHandler = new FileHandler("manager.xml");
            fileHandler.setFormatter(new XMLFormatter());
            log.addHandler(fileHandler);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Task add(String name, String description, Date date) {
        Task task = new Task();
        task.setName(name);
        task.setDescription(description);
        task.setDate(date);
        dao.add(task);
        //log.info(String.format("Task %s added", task.getName()));
        return task;
    }

    public Task update(int id, String name, String description, Date date, int version) {
        Task task = new Task();
        task.setId(id);
        task.setName(name);
        task.setDescription(description);
        task.setDate(date);
        task.setVersion(version + 1);
        dao.update(id, task);
        //log.info(String.format("Task %s updated", task.getName()));
        return task;
    }

    public void delete(int id) {
        dao.delete(id);
        //log.info(String.format("Task with id %d deleted", id));
    }

    public boolean checkVersion(int id, int version) {
        Task task = dao.getTaskFromStorage(id);
        if (task != null && version == task.getVersion()){
            return true;
        }
        return false;
    }

    public void refresh(){
        dao.refresh();
    }

    public List<Task> getTasks(){
        return dao.getAllTasks();
    }

    public List<Task> getExpiredTasks() {
        List<Task> expiredTask = new SortedList<Task>(new DateComparator());
        Date date = new Date();
        for (Task task : dao.getAllTasks()) {
            if (date.compareTo(task.getDate()) > 0) {
                expiredTask.add(task);
            }
        }
        return expiredTask;
    }

    public Task getTask(int id){
        return dao.getTask(id);
    }
}
